<template>
  <el-menu
    :default-active="activeIndex2"
    class="el-menu-demo"
    mode="horizontal"
    v-bind="$attrs"
    :background-color="backgroundColor"
    @select="handleSelect"
  >
    <sub-navi
      :current="current"
      :subMenu="naviList"
    ></sub-navi>
  </el-menu>
</template>

<script>
  import { ref } from 'vue'
  import { ElMenu, ElMenuItem } from 'element-plus'
  import { store } from '@naturefw/nf-state'
  // 展示子菜单
  import subNavi from './navi-sub.vue'
  // 路由
  import { useRouter } from '../router'

const getNavi = (arrNavi, arrPath, index) => {

  const navi = arrNavi.find((item) => item.naviId === arrPath[index])

  if (index === arrPath.length - 1 ) {
    // 最后一级，返回
    return navi
  } else {
    return getNavi(navi.children, arrPath, index + 1)
  }
}

</script>

<script setup>
  
  const props = defineProps({
    'background-color': { // 默认背景色
      type: String,
      default: '#ece5d9'
    },
    itemProps: Object
  })

  const router = useRouter()

  // 获取状态和导航内容
  const { current, naviList } = store
  // 激活第一个导航项，或者路由
  const activeIndex2 = ref((router.naviId)?? naviList[0].naviId)
  

  const handleSelect = (key, keyPath) => {
    // console.log(key, keyPath)

    const navi = getNavi(naviList, keyPath, 0)
    if (navi.link === 'menu') {
      // 打开菜单
      current.naviId = key
    } else {
      // 打开连接
      window.open(navi.link, '_blank')
    }
  }

</script>
